package com.weibotwo.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.weibotwo.common.Exception.UserServiceException;
import com.weibotwo.common.util.FaceFormat;
import com.weibotwo.common.util.PageResult;
import com.weibotwo.dao.*;
import com.weibotwo.pojo.*;
import com.weibotwo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import java.util.*;

/**
 * 用戶操作實現類
 * UserServiceImpl
 *
 * @author 天火
 * @version 1.0
 * @date 2019-02-28
 */
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private WeiboTabMapper weiboTabMapper;

    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private ShellMapper shellMapper;

    @Autowired
    private MainDao mainDao;

    @Autowired
    private SecondMapper secondMapper;

    /**
     * 用户登录
     * 通过用户邮箱和密码查找用户,当存在用户时返回用户信息，如果不存在则抛出异常
     * 获得用户上次登陆的时间
     * 判断用户上次登陆时间和当前时间是不是同一天，如果是同一天则为用户增加积分并保存获取积分记录
     */
    public User login(String userId, String password) throws UserServiceException {
        User user = new User();
        try {
            String passwordMD5 = DigestUtils.md5DigestAsHex(password.getBytes());
            user = userDao.findUserByEmailAndPassword(userId, passwordMD5);
            if (user.getBanTime() == null) {
                Calendar calendar = Calendar.getInstance(); //时间数据处理
                calendar.setTime(user.getLastLogin());
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                Date start = calendar.getTime();
                if (new Date().getTime() - start.getTime() > 1000 * 60 * 60 * 24) {

                    user.setConchIntegral(user.getConchIntegral() + 20);
                }
                user.setLastLogin(new Date());
                return user;
            } else {
                throw new UserServiceException("账号被封至" + user.getBanTime());
            }

        } catch (Exception e) {
            throw new UserServiceException("用户名密码错误");
        }
    }

    @Override
    public PageResult findWeiboListByUserId(Long userId, Integer pageNum, Integer pageSize,String action) {

        PageHelper.startPage(pageNum, pageSize);
        WeiboTabExample example = new WeiboTabExample();
        WeiboTabExample.Criteria criteria = example.createCriteria();
        criteria.andUIdEqualTo(userId);
        //获得微博条件
        if("me".equals(action)){
            criteria.andMTStateEqualTo(0L);
        }else if("trans".equals(action)){
            criteria.andMTStateEqualTo(1L);
        }
        example.setOrderByClause("m_date DESC");
        List<WeiiBoPojo> weiiBoPojos = weiboTabMapper.selectByExample(example);
        weiiBoPojos = FaceFormat.formt(weiiBoPojos); //格式化微博
        for (WeiiBoPojo weibo : weiiBoPojos) {
            if (weibo.getmLike() != null) {
                if (weibo.getmLike() > 0)
                    weibo.setB(true);
            } else {
                weibo.setB(false);
            }
            User user = userDao.findUserById(weibo.getuId());
            weibo.setUser(user);
        }
        Page<WeiiBoPojo> pageWeibo = (Page<WeiiBoPojo>) weiiBoPojos;
        PageResult pageResult = new PageResult();
        pageResult.setTotals((int) pageWeibo.getTotal());
        pageResult.setPageTotals(pageWeibo.getPages());

        pageResult.setRows(pageWeibo.getResult());
        return pageResult;
    }

    @Override
    public void register(User user) {
        try {
            String passwordMD5 = DigestUtils.md5DigestAsHex(user.getPassword().getBytes()); //密码加密
            user.setPassword(passwordMD5);
            user.setRegisterTime(new Date());        //使用当前时间作为用户注册时间
            user.setLastLogin(new Date());           //设置登陆时间
            user.setBirthday("2019-1-1");           //设置默认日期
            user.setIntegral(50);//增加用户积分50
            PointRecord record = new PointRecord();
            addIntegralRecord(record, user, 1L);
            userDao.addUser(user);    //保存用户注册信息
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateUser(User user) {
        try {
            userDao.updateUserInfo(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public User findUserByID(Long uId) {
        User user = userDao.findUserById(uId);
        return user;
    }

    /**
     * 消息通知，将用户的欸被评论，点赞，私信等消息通知给登陆用户
     */
    public Map<String, Object> alerts(Long uId) {
        Map<String, Object> map = new HashMap<>();
        try {
            //未读私信
            int num = friendMapper.findUnreadMNum(uId);
            map.put("unRMNum", num);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @Override
    public User findUserByEmail(String eMail) {
        return userDao.findUserByEmail(eMail);
    }

    @Override
    public PageResult findCollectWeiboByUserId(Long uId, int pageNum) {
        List<Long> mIds = userDao.findCollectWeiboByUserid(uId);
        PageHelper.startPage(pageNum, 10);
        WeiboTabExample example = new WeiboTabExample();
        WeiboTabExample.Criteria criteria = example.createCriteria();
        criteria.andMIdIn(mIds);
        criteria.andMStateEqualTo(0L);
        example.setOrderByClause("m_date desc");
        List<WeiiBoPojo> weiiBoPojos = weiboTabMapper.selectByExample(example);
        for (WeiiBoPojo weiiBoPojo : weiiBoPojos) {
            weiiBoPojo.setUser(userDao.findUserById(weiiBoPojo.getuId()));
        }
        Page<WeiiBoPojo> weiiBoPojoPage = (Page<WeiiBoPojo>) weiiBoPojos;
        PageResult result = new PageResult();
        result.setPageTotals(weiiBoPojoPage.getPages());
        result.setTotals((int) weiiBoPojoPage.getTotal());
        result.setRows(weiiBoPojoPage.getResult());
        return result;
    }

    /**
     * 贝壳分页结果
     *
     * @param user
     * @param operation
     * @param pageNum
     * @return
     */
    @Override
    public Map<String, Object> shellIndex(User user, String operation, Integer pageNum) {
        Map<String, Object> map = new HashMap<>();
        List<Shell> list = null;
        PageHelper.startPage(pageNum, 10);
        try {
            if ("NEWS".equals(operation)) {
                list = shellMapper.findShellByNews();
            } else if ("SOLVE".equals(operation)) {
                list = shellMapper.findShellByState(1L);
            } else if ("UNSOLVE".equals(operation)) {
                list = shellMapper.findShellByState(0L);
            } else if ("ME".equals(operation)) {
                if (user == null) {
                    return null;
                }
                list = shellMapper.findShellByUserId(user.getId());
            }

            for (Shell shell : list) {
                shell.setChUser(userDao.findUserById(shell.getUserId()));
            }

            list = FaceFormat.shellFormt(list);        //标签格式转换
            Page<Shell> shellPage = (Page<Shell>) list;
            map.put("shellList", shellPage.getResult());
            map.put("pageNum", pageNum);
            map.put("totalPage", shellPage.getPages());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 显示贝壳细节
     *
     * @param shellId 贝壳Id
     * @return map
     */
    public Map<String, Object> shellDetail(long shellId) {
        Map<String, Object> map = new HashMap<>();
        try {
            Shell shell = shellMapper.findShellById(shellId);
            shell.setChUser(userDao.findUserById(shell.getUserId()));
            shell.setShellBody(FaceFormat.conchFormt(shell.getShellBody()));
            map.put("shell", shell);

            //获取海螺问题的评论
            List<WeiboComm> list = mainDao.findWeiboComm(shellId);
            list = FaceFormat.commFormt(list);
            for (WeiboComm weiboComm : list) {
                weiboComm.setCommUser(userDao.findUserById(weiboComm.getCommentId()));
            }
            map.put("conchComm", list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 发布神奇贝壳
     *
     * @param shell 实体类
     */
    public void publishShell(Shell shell) {
        try {
            shellMapper.saveShell(shell);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 采纳海螺答案，设置海螺评论状态为101，设置海螺状态为1
     *
     * @param shellId
     * @param commId
     */
    public void adoptComm(long shellId, long commId) {
        try {
            //设置海螺状态为1
            secondMapper.setShellState(shellId);
            //设置海螺评论状态为101
            secondMapper.setShellComm(commId);
            //为用户增加海螺积分
            Shell shell = shellMapper.findShellById(shellId);
            User user = userDao.findUserById(secondMapper.findUserIdByCommId(commId));
            user.setConchIntegral(user.getConchIntegral() + shell.getsNumber());
            userDao.updateUserInfo(user);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存积分流水信息(旧)
     */
    public void addIntegralRecord(PointRecord record, User user, Long actionId) {
        try {
            record.setemail(user.getEmail());
            record.setRecordDate(new Date());
            record.setAction(actionId);
            secondMapper.addIntegralRecord(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
